﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Util.Library.ServiceExtensions
{

    /// <summary>
    /// Startup扩展
    /// </summary>
    public static class StartupSetup
    {
        /// <summary>
        /// ConfigureServices调用
        /// </summary>
        /// <param name="services"></param>
        public static void AddServices(this IServiceCollection services)
        {
            CallStartupMethods(services, "ConfigureServices");
        }

        /// <summary>
        /// Configure调用
        /// </summary>
        /// <param name="app"></param>
        public static void AddConfigure(this IApplicationBuilder app)
        {
            CallStartupMethods(app, "Configure");
        }

        /// <summary>
        /// Add services to the container
        /// Configure the HTTP request pipeline
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="methodName"></param>
        private static void CallStartupMethods(object parameter, string methodName)
        {
            foreach (var assembly in GlobalAssemblies.AllAssemblies)
            {
                var startupType = assembly.GetTypes()
                    .FirstOrDefault(t => typeof(IStartup).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);

                if (startupType == null) continue;

                var method = startupType.GetMethod(methodName)
                    ?? throw new InvalidOperationException($"Method '{methodName}' not found in type '{startupType.Name}'.");

                method.Invoke(Activator.CreateInstance(startupType), new[] { parameter });
            }
        }
    }
}
